package com.xj;

import cn.hutool.core.lang.JarClassLoader;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author ricky
 * @date 2022/4/29 16:31
 */
@SpringBootApplication
public class JarTestApp {
    public static String lx = "0";
    private static String[] files = {"jar/otherJar1-1.0.jar", "jar/otherJar2-1.0.jar"};

    @SneakyThrows
    public static void main(String[] args) {
        if (args.length > 0) {
            lx = args[0];
        }
        System.out.println("lx = " + lx);
        try {
            for (String filePath : files) {
                ClassPathResource classPathResource = new ClassPathResource("/" + filePath);
                try (InputStream inputStream = classPathResource.getInputStream();
                     OutputStream outputStream = FileUtils.openOutputStream(new File(filePath));) {
                    IOUtils.copy(inputStream, outputStream);
                }
            }
        } catch (Exception e) {
            System.exit(0);
            return;
        }
        if ("0".equals(JarTestApp.lx)) {
            ClassLoader classLoader = JarClassLoader.loadJarToSystemClassLoader(new File("jar/otherJar1-1.0.jar"));
        } else if ("1".equals(JarTestApp.lx)) {
            ClassLoader classLoader = JarClassLoader.loadJarToSystemClassLoader(new File("jar/otherJar2-1.0.jar"));
        }
        // URLClassLoader classLoader = (URLClassLoader) ClassUtils.getDefaultClassLoader();
        // Method add = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        // boolean accessible = add.isAccessible();
        // add.setAccessible(true);
        // URI uri = new File("jar/otherJar1-1.0.jar").toURI();
        // add.invoke(classLoader, uri.toURL());
        // add.setAccessible(accessible);

        SpringApplication.run(JarTestApp.class, args);
    }
}
